var express = require('express');
var router = express.Router();

const collection = require("../models/collection")
const question = require("../models/question")
const point = require("../models/point")

const formidable = require('formidable');

router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            collection.find({
                UUID: fields.UUID
            }, {
                attachment: 1,
                question_ID: 1, // point_id 
                _id: 0
            }, (error, id_list) => {
                if (error) {
                    res.json({ 'state': false, 'msg': error });
                } else {

                    let question_id_list = []
                    let point_id_list = []
                    for (let i = 0; i < id_list.length; i++) {
                        if (id_list[i].attachment == true) point_id_list.push(id_list[i].question_ID)
                        else if (id_list[i].attachment == false) question_id_list.push(id_list[i].question_ID)
                    }

                    var getCollectedQuestion_one = () => {
                        return new Promise(function (resolve, reject) {
                            question.find({
                                _id: {
                                    $in: question_id_list
                                }
                            }, (err, list_one) => {
                                if (err) {
                                    res.json({ 'state': false, 'msg': err });
                                } else {
                                    resolve(list_one)
                                }
                            })
                        })

                    }

                    var getCollectedQuestion_two = (list_one) => {
                        point.find({
                            _id: {
                                $in: point_id_list
                            }
                        }, (err, list_two) => {
                            if (err) {
                                res.json({ 'state': false, 'msg': err });
                            } else {
                                res.json({ 'state': true, 'result': {
                                    extraQuestion: list_one,
                                    attachedQuestion: list_two
                                }});
                                return
                            }
                        })
                    }

                    getCollectedQuestion_one().then(getCollectedQuestion_two)


                }
            })
        }

    });

});

module.exports = router;